/**
 * Sep 27, 2013 11:17:57 AM
 * com.kratonsolution.belian.kernel.service
 * PrimaryKeyGenerator.java
 */
package com.kratonsolution.belian.kernel.service;

import java.util.UUID;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.kratonsolution.belian.kernel.dm.Model;

/**
 * @author Agung Dodi Perdana
 * @email agung.dodi.perdana@gmail.com
 * @Version Sinch 0.0.1
 */
@Component
@Aspect
public class PrimaryKeyGenerator
{
    Logger log = Logger.getLogger(getClass());
    
    @Before("@annotation(com.kratonsolution.belian.kernel.service.AutoInjectPrimaryKey)")
    public void generate(JoinPoint point)
    {
        Model model = null;
        
        for(Object object:point.getArgs())
        {
            if(object instanceof Model)
            {
                model = (Model)object;
                break;
            }
        }
        
        log.info("generating primary key for ["+model.getClass().getSimpleName()+"]");
        log.info("Checking custom primary key ["+model.getCustomPrimaryKey()+"]");
        
        if(Strings.isNullOrEmpty(model.getCustomPrimaryKey()))
            model.setId(UUID.randomUUID().toString());
        else
            model.setId(model.getCustomPrimaryKey());
    }
}
